<template>
  <div class="app-container">
    <el-card shadow="never">
      <!-- 警告区域 -->
      <el-alert
        show-icon
        :title="$t('user.tip')"
        type="warning"
        :closable="false"
      ></el-alert>
      <!-- 选择分类区域 -->
      <el-row
        class="cat_opt"
        style="margin-top:10px"
      >
        <el-col>
          <span>{{$t('user.select')}}：</span>
          <!-- 选择框 -->
          <el-select
            v-model="selected"
            filterable
            clearable
            :placeholder="$t('common.select')"
            @change="fetchHealthData"
          >
            <el-option
              v-for="item in optionfen"
              :key="item.user_id"
              :label="item.username"
              :value="{ value: item.username, key: item.user_id}"
            >
            </el-option>
            <div style="bottom: -10px">
              <el-pagination
                small
                @current-change="handleCurrentChange"
                :current-page="currentpage"
                :page-size="pageSize"
                layout="prev, pager,next,total"
                :total="userList.length"
              >
              </el-pagination>
            </div>
          </el-select>
        </el-col>
      </el-row>

      <!-- 所有证书列表 -->
      <el-table
        :data="health_data"
        border
        stripe
        style="margin-top:10px"
      >

        <el-table-column
          align="center"
          width="50"
          :label="$t('usermachine.table.user_id')"
        >
          <!-- <template slot-scope="scope">
            {{ scope.row.user_id }}
          </template> -->

          {{this.selectedUserObj.key}}

        </el-table-column>

        <el-table-column
        :label="$t('usermachine.table.record')"
          width="100"
          align="center"
        >
          <el-table-column
          :label="$t('usermachine.table.weight')"
            align="center"
          >

            <div
              class='com-chart'
              ref='weight_ref'
              :style="{width: '100%' , height:'100%'}"
            ></div>

          </el-table-column>

          <el-table-column
          :label="$t('usermachine.table.bloodPressure')"
            align="center"
          >

            <div
              class='com-chart'
              ref='blood_pressure_ref'
              :style="{width: '100%' , height:'100%'}"
            ></div>

          </el-table-column>

          <el-table-column
            align="center"
            :label="$t('usermachine.table.bloodSugar')"
          >

            <div
              class='com-chart'
              ref='blood_sugar_ref'
              :style="{width: '100%' , height:'100%'}"
            ></div>

          </el-table-column>

        </el-table-column>

        <el-table-column
          align="center"
          width="100"
          :label="$t('usermachine.table.goal')"
        >

          <el-table-column
            align="center"
            width="150"
            :label="$t('usermachine.table.weight')"
          >

            {{this.data_targer.weight_target}}

          </el-table-column>

          <el-table-column
            align="center"
            width="150"
            :label="$t('usermachine.table.bloodPressure')"
          >
            {{this.data_targer.blood_pressure_target}}

          </el-table-column>

          <el-table-column
            align="center"
            width="150"
            :label="$t('usermachine.table.bloodSugar')"
          >
            {{this.data_targer.blood_sugar_target}}
          </el-table-column>

        </el-table-column>

        <el-table-column
          :label="$t('common.operate')"
          align="center"
          width="200"
          class-name="small-padding fixed-width"
        >
          <template>
            <el-button
              type="primary"
              size="mini"
              @click="goMachineList"
            >{{$t('common.see')}}</el-button>
            <br /><br />
            <el-button
              type="success"
              size="mini"
              @click="showAddDialog"
            >
            {{$t('common.add')}}
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="delTarget"
            >
            {{$t('common.delete')}}
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <!-- 对话框 -->
      <el-dialog
        title="添加目标信息"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          style="width: 80%"
          :model="target_form"
          :rules="rules"
          ref="ruleForm"
        >
          <el-form-item
            label="用户ID："
            label-width="120px"
            prop="user_id"
          >
            <el-input
              autocomplete="off"
              v-model.number="target_form.user_id"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="目标时间："
            label-width="120px"
            prop="target_date"
          >
            <!-- <el-date-picker
              v-model="target_form.target_date"
              type="date"
              placeholder="选择日期时间"
              value-format="timestamp"
              style="width: 100%"  
            >
            </el-date-picker> -->
            <el-input
              autocomplete="off"
              v-model="target_form.target_date"
              placeholder="格式：xxxx-xx-xx"
            ></el-input>

          </el-form-item>

          <el-form-item
            label="体重："
            label-width="120px"
            prop="weight"
          >
            <el-input
              autocomplete="off"
              v-model.number="target_form.weight_target"
            ></el-input>

          </el-form-item>

          <el-form-item
            label="血压："
            label-width="120px"
            prop="blood_pressure"
          >
            <el-input
              autocomplete="off"
              v-model.number="target_form.blood_pressure_target"
            ></el-input>

          </el-form-item>

          <el-form-item
            label="血糖："
            label-width="120px"
            prop="blood_sugar"
          >
            <el-input
              autocomplete="off"
              v-model.number="target_form.blood_sugar_target"
            ></el-input>

          </el-form-item>

          <el-form-item
            label="创建时间："
            label-width="120px"
            prop="create_time"
          >
            <el-input
              autocomplete="off"
              v-model="target_form.create_time"
            ></el-input>

          </el-form-item>

          <el-form-item
            label="更新时间："
            label-width="120px"
            prop="update_time"
          >
            <el-input
              autocomplete="off"
              v-model="target_form.update_time"
            ></el-input>

          </el-form-item>

        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addTarget"
          >确 定</el-button>
        </div>
      </el-dialog>

    </el-card>
  </div>
</template>
  

<script>
import healthmanage from "@/api/healthmanage";
import { Collapse } from "element-ui";
export default {
  name: "machinelist",
  data() {
    return {
      selected: "", //输入框的值
      userList: [], //用户列表总数据
      optionfen: [], //当前页码的数据
      currentpage: 1, //当前页码
      pageSize: 8, //每页展示的条数

      page_num: 1,

      weight_chartInstance: null,
      blood_pressure_chartInstance: null,
      blood_sugar_chartInstance: null,
      selectedUserObj: {}, //选中对象
      health_data: [], //健康档案和目标
      data_targer: {}, //健康目标
      data_machine: [], // 健康档案
      dialogFormVisible: false, //对话框（查看）
      target_form: {},
      rules: {
        user_id: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        target_date: [
          {
            required: true,
            message: "请选择目标日期",
            trigger: "blur",
          },
        ],
        weight_target: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        blood_pressure_target: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        blood_sugar_target: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        create_time: [
          { required: true, message: "请输入内容", trigger: "blur" },
        ],
        update_time: [
          { required: true, message: "请输入内容", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.fetchUserList();
  },
  destroyed() {
    window.removeEventListener("resize", this.screenAdapter);
  },
  methods: {
    //选择框分页
    //分页的实现,currentpage 为页码，每页展示的数据为8（可自行更改pageSize）条，分别是在总数据userList中
    handleCurrentChange(val) {
      this.optionfen = [];
      this.currentpage = val;
      let start = (val - 1) * this.pageSize;
      let end = Number(start) + Number(this.pageSize);
      //此处需要判断如果计算的结束下标大于总数据的长度，则需要修改结束下标
      if (end > this.userList.length) {
        end = this.userList.length;
      }
      for (let i = start; i < end; i++) {
        //将取到的数据展示在页面
        this.optionfen.push(this.userList[i]);
      }
      // console.log(this.optionfen);
    },
    //获取选项框用户列表
    fetchUserList() {
      var vm = this;
      healthmanage
        .getUserList(this.page_num, 100)
        .then((res) => {
          // console.log(res);
          this.userList = res.data.userList.list;
          // console.log(this.userList);
          for (let i = 0; i < 8; i++) {
            //将取到的数据展示在页面
            this.optionfen.push(this.userList[i]);
          }
        })
        .catch((error) => {});
    },
    //获取健康档案列表
    fetchHealthData(selectedUser) {
      this.selectedUserObj = selectedUser;

      // console.log(this.selectedUserObj.key)
      healthmanage
        .getHealthData(this.selectedUserObj.key)
        .then((res) => {
          //清空表格数据
          this.health_data = [];
          this.data_targer = {};
          this.data_machine = [];

          // console.log(res);
          if (res.data.target != null) {
            this.health_data.push(res.data);
            this.data_machine.push(res.data.bodyData);
            this.data_targer = res.data.target;

            //动态加载ECharts
            this.$nextTick(() => {
              this.initChart();
              this.updateChart();
              window.addEventListener("resize", this.screenAdapter);
              this.screenAdapter();
            });
          } else {
            //提示
            this.$message({
              type: "error",
              message: "该用户暂无健康数据！",
            });
          }
        })
        .catch((error) => {});
    },
    //创建图表
    initChart() {
      //创建实例对象
      this.weight_chartInstance = this.$echarts.init(this.$refs.weight_ref);
      this.blood_pressure_chartInstance = this.$echarts.init(
        this.$refs.blood_pressure_ref
      );
      this.blood_sugar_chartInstance = this.$echarts.init(
        this.$refs.blood_sugar_ref
      );

      //配置初始图表
      const weightInitOption = {
        grid: {
          top: "10%",
          left: "5%",
          right: "5%",
          bottom: "6%",
          containLabel: true,
        },
        tooltip: {
          show: true,
        },
        xAxis: {
          type: "category",
          // data: [],
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            lineStyle: {
              type: "dotted",
              color: "#eee",
            },
          },
        },
        series: [
          {
            type: "line",
            // data: [100, 200, 300, 250, 150, 180, 220],
            itemStyle: {
              color: "#26547C",
            },
          },
        ],
      };
      const bloodPressureInitOption = {
        grid: {
          top: "10%",
          left: "5%",
          right: "5%",
          bottom: "6%",
          containLabel: true,
        },
        tooltip: {
          show: true,
        },
        xAxis: {
          type: "category",
          // data: [],
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            lineStyle: {
              type: "dotted",
              color: "#eee",
            },
          },
        },
        series: [
          {
            type: "line",
            // data: [100, 200, 300, 250, 150, 180, 220],
            itemStyle: {
              color: "#EF476F",
            },
          },
        ],
      };
      const bloodSugarInitOption = {
        grid: {
          top: "10%",
          left: "5%",
          right: "5%",
          bottom: "6%",
          containLabel: true,
        },
        tooltip: {
          show: true,
        },
        xAxis: {
          type: "category",
          // data: [],
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            lineStyle: {
              type: "dotted",
              color: "#eee",
            },
          },
        },
        series: [
          {
            type: "line",
            // data: [100, 200, 300, 250, 150, 180, 220],
            itemStyle: {
              color: "#FFD166",
            },
          },
        ],
      };

      //设置初始图表

      this.weight_chartInstance.setOption(weightInitOption);
      this.blood_pressure_chartInstance.setOption(bloodPressureInitOption);
      this.blood_sugar_chartInstance.setOption(bloodSugarInitOption);
    },
    //更新图表
    updateChart() {
      // console.log(this.data_machine)

      //获取体重、血压、血糖数据
      const weightValueArr = this.data_machine[0].map((item) => {
        return item.weight;
      });
      const bloodPressureValueArr = this.data_machine[0].map((item) => {
        return item.blood_pressure;
      });
      const bloodSugarValueArr = this.data_machine[0].map((item) => {
        return item.blood_sugar;
      });

      //配置数据
      const weightDataOption = {
        series: [
          {
            data: weightValueArr,
          },
        ],
      };
      const bloodPressureDataOption = {
        series: [
          {
            data: bloodPressureValueArr,
          },
        ],
      };
      const bloodSugarDataOption = {
        series: [
          {
            data: bloodSugarValueArr,
          },
        ],
      };

      //更新图表

      this.weight_chartInstance.setOption(weightDataOption);
      this.blood_pressure_chartInstance.setOption(bloodPressureDataOption);
      this.blood_sugar_chartInstance.setOption(bloodSugarDataOption);
    },
    //图表自适应
    screenAdapter() {
      this.weight_chartInstance.resize();
      this.blood_pressure_chartInstance.resize();
      this.blood_sugar_chartInstance.resize();
    },
    //查看档案
    goMachineList() {
      // console.log(this.selectedUserObj.key)
      this.$router.push({
        path: "/HealthyManger/MachineList",
        query: { user_id: this.selectedUserObj.key },
      });
    },
    //添加目标显示
    showAddDialog() {
      this.dialogFormVisible = true;
      this.target_form = {};
    },
    //添加（更新）目标
    addTarget() {
      console.log(this.target_form);
      this.$refs.ruleForm.validate(async (success) => {
        //如果全部字段符合条件
        if (success) {
          this.dialogFormVisible = false;
          let result = await healthmanage.addOrEditTarget(this.target_form);
          if (result.errorCode == 0) {
            this.$message({
              type: "success",
              message: "添加目标信息成功",
            });
            this.fetchHealthData(this.selectedUserObj);
          }
        } else {
          vm.$message.error("error");
          console.log(error);
        }
      });
    },
    //删除目标
    delTarget() {
      this.$confirm("此操作将永久删除该目标信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用接口
          healthmanage.delTarget(this.selectedUserObj.key).then((res) => {
            //提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新页面数据
            this.fetchHealthData(this.selectedUserObj);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
